import { ClassData, mockClasses } from '../mock/classData';

// 班级管理服务接口
export interface IClassService {
  getClasses(): Promise<ClassData[]>;
  getClass(id: string): Promise<ClassData | undefined>;
  addClass(classData: Omit<ClassData, 'id'>): Promise<ClassData>;
  updateClass(id: string, classData: Partial<ClassData>): Promise<ClassData | null>;
  deleteClass(id: string): Promise<boolean>;
}

// 班级管理服务实现类
export class ClassService implements IClassService {
  private readonly STORAGE_KEY = 'classes';
  private classes: ClassData[] = [];
  private isInitialized = false;

  // 初始化数据
  private async initialize(): Promise<void> {
    if (this.isInitialized) return;
    
    try {
      // 直接使用最新的mock数据，不依赖localStorage
      const { mockClasses } = await import('../mock/classData');
      this.classes = [...mockClasses];
      
      // 清除旧的localStorage数据
      localStorage.removeItem(this.STORAGE_KEY);
      localStorage.removeItem('classes');
  localStorage.removeItem('classData');
  localStorage.removeItem('class_info');
    } catch (error) {
      console.error('初始化班级数据失败:', error);
      throw new Error('初始化班级数据失败');
    }
    
    this.isInitialized = true;
    this.classes = [...mockClasses];
  localStorage.setItem('classes', JSON.stringify(this.classes));
  }

  // 保存到localStorage
  private saveToStorage(): void {
    localStorage.setItem(this.STORAGE_KEY, JSON.stringify(this.classes));
  }

  // 获取所有班级
  async getClasses(): Promise<ClassData[]> {
    await this.initialize();
    return [...this.classes];
  }

  // 获取单个班级
  async getClass(id: string): Promise<ClassData | undefined> {
    await this.initialize();
    return this.classes.find(cls => cls.id === id);
  }


  // 添加班级
  async addClass(classData: Omit<ClassData, 'id'>): Promise<ClassData> {
    await this.initialize();
    
    const newClass: ClassData = {
      ...classData,
      id: Date.now().toString()
    };
    
    this.classes.push(newClass);
    this.saveToStorage();
    
    return newClass;
  }

  // 更新班级
  async updateClass(id: string, classData: Partial<ClassData>): Promise<ClassData | null> {
    await this.initialize();
    
    const index = this.classes.findIndex(cls => cls.id === id);
    if (index === -1) {
      return null;
    }
    
    this.classes[index] = {
      ...this.classes[index],
      ...classData
    };
    
    this.saveToStorage();
    return this.classes[index];
  }

  // 删除班级
  async deleteClass(id: string): Promise<boolean> {
    await this.initialize();
    
    const index = this.classes.findIndex(cls => cls.id === id);
    if (index === -1) {
      return false;
    }
    
    this.classes.splice(index, 1);
    this.saveToStorage();
    
    return true;
  }
}

// 创建单例实例
export const classService = new ClassService();